//
//  CategorySearchController.m
//  Tang
//
//  Created by 352324497@qq.com on 15/12/7.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "CategorySearchController.h"
#import "CategoryModel.h"
#import "CategorySearchCell.h"
#import "ScrollViewTableController.h"
#import "CategorySegmentViewController.h"
#import "SearchHistoryViewController.h"
@interface CategorySearchController ()<UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)NSMutableArray *categoryArray;
@property (nonatomic, strong)NSMutableArray *titleArray;
@property (nonatomic, strong)NSString *text;
@end

@implementation CategorySearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"搜索分类";
    
    [self requestData];
    
    // 返回按钮的自定义
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 25, 25);
    [button addTarget:self action:@selector(BackButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarbutton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftBarbutton;
    
    // collectionCiew
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 50 * Kx6, KWidth, KHeight - 114 * Kx6) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[CategorySearchCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    
    [self requestNextData];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake((KWidth - 250 * Kx6) / 2, 10 * Kx6 , 250 * Kx6, 40 * Kx6)];
    self.searchBar.barStyle = UIBarButtonSystemItemDone;
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    // 取消键的颜色
    self.searchBar.tintColor = [UIColor lightGrayColor];
    self.searchBar.searchBarStyle = UIBarStyleBlackTranslucent;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索你感兴趣的宝贝";
    [self.view addSubview:_searchBar];
}
-(void)requestData
{
    NSString *url = @"http://open3.bantangapp.com/category/list";
    NSString *string = @"app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&track_device_info=iPhone6%2C2&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8";
    NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    
    self.categoryArray = [NSMutableArray array];
    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"请求失败");
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSArray *array = Dic[@"data"];

        self.categoryArray = [NSMutableArray array];
        for (NSDictionary *dic in array)
        {
            CategoryModel *model = [[CategoryModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
//            NSLog(@"name ==== %@", model.name);
            [self.categoryArray addObject:model];
//            NSLog(@"title === %@", self.categoryArray);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    }]resume];

}


#pragma mark - 请求下一页面的数据
-(void)requestNextData
{
    NSString *url = @"http://open3.bantangapp.com/base/search/hottags";
    NSString *string = @"app_installtime=1449053241.284786&app_versions=5.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&screensize=640&track_device_info=iPhone6%2C2&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=9";
    NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"请求失败");
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.titleArray = [NSMutableArray array];
        self.titleArray = Dic[@"data"];
    }]resume];
}


#pragma mark - 是否开始编辑
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    searchBar.showsCancelButton = YES;
    searchBar.frame = CGRectMake((KWidth - 300 * Kx6) / 2, 10 * Kx6 , 300 * Kx6, 40 * Kx6);
    UIButton *btn=[searchBar valueForKey:@"_cancelButton"];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    SearchHistoryViewController *vv = [[SearchHistoryViewController alloc]init];
    vv.titleArray = [NSMutableArray array];
    if (self.titleArray.count != 0)
    {
        vv.titleArray = self.titleArray;
    }
    [self.navigationController pushViewController:vv animated:NO];
    [self.searchBar resignFirstResponder];
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
//    NSLog(@"222222");
    return YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
//    NSLog(@"333333");
}

#pragma mark - 输入过程一直在调用
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//    NSLog(@"ssssssss");
}

#pragma mark - 点击取消键的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.frame = CGRectMake((KWidth - 250 * Kx6) / 2, 10 * Kx6 , 250 * Kx6, 40 * Kx6);
    searchBar.text = nil;
    // 使键盘回收
    [searchBar resignFirstResponder];
    
}

#pragma mark - 返回的方法
- (void)BackButtonAction:(UIButton *)btn
{
    [self.searchBar removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - collection
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.categoryArray.count != 0)
    {
        return self.categoryArray.count;
    }
    return 0;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10 * Kx6, 10 * Kx6, 10 * Kx6, 10 * Kx6);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((KWidth - 32 * Kx6) / 2, (KWidth - 30 * Kx6) / 4);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CategorySearchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (self.categoryArray.count != 0)
    {
        CategoryModel *model = self.categoryArray[indexPath.item];
        cell.model = model;
        cell.backgroundColor = [UIColor whiteColor];
        cell.layer.cornerRadius = 5 * Kx6;
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchBar removeFromSuperview];
    CategoryModel *model = self.categoryArray[indexPath.item];
    ScrollViewTableController *scriollVC = [[ScrollViewTableController alloc]initWithStyle:(UITableViewStylePlain)];
    scriollVC.isCategory = YES;
    scriollVC.ID = model.ID;
    scriollVC.name = model.name;
    [self.navigationController pushViewController:scriollVC animated:NO];
    
}
-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
